/**
 * 
 */
package instant.openvfs.home.web;

import instant.openvfs.home.Debug;

import java.io.InputStream;

import jvs.vfs.FileSystem;
import x.java.io.File;
import android.net.Uri;
import android.util.Log;

/**
 * @author qiangli
 * 
 */
public class FileHandler {
private static final String TAG = "FileHandler";

//	private static final SimpleDateFormat cdf = new SimpleDateFormat(
//			"yyyy-MM-dd.HH.mm.ss.SSS");

	public FileHandler() {
	}

	public Object handle(Uri uri, String mode) throws Exception {
		File file = new File(uri.getPath());
		if (Debug.DEBUG) {
			Log.d(TAG, "handle uri: "+uri + " mode: " + mode + " file: " + file);
		}
		try {
			if (!file.exists()) {
				return fileNotFound(file);
			}
			
			if (!file.canRead()) {
				return fileAccessDenied(file);
			}

			if (file.isDirectory()) {     
				return listFiles(uri, file);
			}

			return loadFile(uri, file);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	protected String fileAccessDenied(File file) {
		if (Debug.DEBUG) {
			Log.d(TAG, "fileAccessDenied: " + file);
		}
		String c = "<html><body><h1>Access denied: " + file.getPath()
				+ "</h1></body></html>";
		return c;
	}

	protected String fileNotFound(File file) {
		if (Debug.DEBUG) {
			Log.d(TAG, "fileNotFound: " + file);
		}
		String c = "<html><body><h1>File " + file.getPath()
				+ " not found</h1></body></html>";
		return c;
	}

	protected String guessType(File file) {
		return FileSystem.getFileSystem().guessType(file);
	}

	protected String listFiles(final Uri uri, final File file) throws Exception {
		throw new Exception("supporte removed " + uri + " file: " + file);
//		if (Debug.DEBUG) {
//			Log.d(TAG, "listFile: " + uri + " file: " + file);
//		}
//		String base = uri.getPath();
//		final int view = getView(uri);
//		
//		//InputStream is = new FolderTemplateInputStream(base, file, view);
//		//return is;
//		return null;
	}

//	private int getView(Uri uri) {
//		try {
//			final int view = Integer.parseInt(uri.getQueryParameter("view"));
//			return view;
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		return 0;
//	}

	protected InputStream loadFile(Uri uri, File file) throws Exception {
		if (Debug.DEBUG) {
			Log.d(TAG, "loadFile: " + uri + " file: " + file);
		}
		return file.getInputStream();
		
//		String base = uri.getPath();
//		String type = file.getContentType();
//		InputStream is = null;
//		if (type != null && type.startsWith("text/")) {
//			is = new FileInputStream(file);
//		} else {
//			is = new FileTypeTemplateInputStream(base, file);
//		}
//		return is;
	}
}
